import os
import requests
from dotenv import load_dotenv
from .download_pdf import download_pdf_by_url
load_dotenv()
API_KEY = os.getenv("SPRINGER_META_API")

def build_springer_query(
    keywords=None,
    title=None,
    author=None,
    abstract=None,

):
    query_parts = []
    if keywords:
        query_parts.append(f"keyword: {keywords}")
    if title:
        query_parts.append(f"title: {title}")
    if author:
        query_parts.append(f"name: {author}")
    if abstract:
        query_parts.append(f"abstract: {abstract}")

    return ' AND '.join(query_parts)

def search_springer(
    keywords=None,
    title=None,
    author=None,
    abstract=None,
    max_results=10,
        download_pdf=False,
        save_dir="./papers"

):
    query = build_springer_query(keywords, title, author, abstract)
    url = f"https://api.springernature.com/meta/v2/json?q={query}&api_key={API_KEY}&p={max_results}"
    resp = requests.get(url)
    data = resp.json()
    results = []

    for record in data['records']:

        if download_pdf and record['url'][1]["value"]:
            # 获取文章URL
            download_url = record['url'][1]["value"]
            download_pdf_by_url(download_url,os.path.join(save_dir,record["title"]+".pdf"))

        results.append({
            "title": record["title"],
            "authors": record.get("creators"),
            "primary_category":record.get("subjects"),
            "summary": record.get('abstract'),
            "publisherName": record.get("publisherName"),
            "publicationDate": record.get("publicationDate"),
            "pdf_url": record['url'][1]["value"],
        })

    return results
